package logic;

import interfaces.Observer;

import java.util.ArrayList;
import java.util.Observable;

import constants.MessageType;

import android.util.Log;
import android.util.Pair;

import models.Mushroom;
import models.PhysicalObject;
import models.Pig;
import models.Wolf;

/**
 * The GameLogicHandler is responsible for updating all active objects
 *
 * @author Knut, Stian
 *
 */
public class GameLogicHandler implements java.util.Observer{

	/*
	 * TAG = the class name used for logging purposes list = the list of game
	 * objects (wolves, mushrooms and the pig) spawnList = the list of objects
	 * waiting to be spawned wolvesList = the list of wolves mushroomsList = The
	 * list of mushrooms
	 *
	 * NOT USED: temp = used to check spawning
	 */

	private static final String TAG = GameLogicHandler.class.getSimpleName();

	private ArrayList<PhysicalObject> list;
	private SpawnAndDespawner spawnList;
	private CollisionHandler colH;
	private ArrayList<Observer> obsList;
	private boolean gameOver = false;

	public GameLogicHandler(ArrayList<PhysicalObject> list, int difficulty) {
		this.list = list;

		spawnList = new SpawnAndDespawner(list,difficulty);
				
		colH = new CollisionHandler(list);
		colH.addObserver((java.util.Observer) list.get(0));
		colH.addObserver(spawnList);
		colH.addObserver(this);

	}

	/*
	 * Update all objects. May be better to add a check to only update those
	 * that are active
	 */
	public synchronized void update() {
		/*
		 * Spawn wolf Get the next wolf in the spawn queue and set its position
		 * and motion values.
		 */

		if (!gameOver) {
			spawnList.spawnWolfTest();
			spawnList.spawnMushroomTest();
		}
		
		//update active objects
		for (PhysicalObject ob : list) {
			if (ob.isActive()) {
				ob.update();
			}
		}
		//check collisions
		if (colH.checkCollisions()) {
			setGameOver(true);
		}

	}

	public boolean isGameOver() {
		return gameOver;
	}

	public void setGameOver(boolean gameOver) {
		this.gameOver = gameOver;
		((Pig) list.get(0)).setGameOver(gameOver);
	}

	@Override
	public void update(Observable observable, Object data) {
		if (data instanceof Pair) {
			@SuppressWarnings({ "rawtypes", "unchecked" })
			Pair<PhysicalObject,MessageType> pair = (Pair)data;
			PhysicalObject ob = pair.first;
			MessageType mt = pair.second;
			
			switch (mt) {
			case COLLISION:	
				setGameOver(true);
				Log.d(TAG,"setter game over");
				break;
			}
		}
		
	}
}
